/**
 * FtpReplyCode.java
 * @author: liuex
 * 2007-12-24 ����03:58:42
 *
 * note: 
 */
package org.lex.net.ftp.util;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.lex.utils.text.Splitter;


public class FTPUtilities {
	// 227 Entering Passive Mode (10,64,130,23,18,184)
	public static SocketAddress parsePasv(String pasv) {
		int from = pasv.indexOf('(');
		int to = pasv.lastIndexOf(')');
		pasv = pasv.substring(from + 1, to);
		String[] tokens = Splitter.CommaSplitter.split(pasv);
		StringBuilder buf = new StringBuilder();
		for (int i = 0; i < 4; i++) {
			buf.append(tokens[i]);
			if (i < 3)
				buf.append('.');
		}
		String host = buf.toString();
		int port = Integer.parseInt(tokens[5]);
		port += 256 * Integer.parseInt(tokens[4]);
		return new InetSocketAddress(host, port);
	}

	public static String generatePortCommand(InetAddress local, int port) {
		StringBuilder buf = new StringBuilder("PORT ");
		byte addr[] = local.getAddress();
		for (int i = 0; i < addr.length; i++)
			buf.append(addr[i] & 0xff).append(',');
		buf.append(port >>> 8 & 0xff).append(',');
		buf.append(port & 0xff);
		return buf.toString();
	}

	public static boolean isPositive(int code) {
		ReplyCode c = new ReplyCode(code);
		if (c.first < 4)
			return true;
		return false;
	}

	static class ReplyCode {
		int first = 0;
		int second = 0;
		int third = 0;

		ReplyCode(int code) {
			this.first = code / 100;
			this.second = (code / 10) % 10;
			this.third = code % 10;
		}
	}
}
